package client.handler;

import java.util.Set;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.MessageContext.Scope;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

/**
 * SOAP handler that stores in the application context the relatesTo field. This
 * will help to determine the correspondence between requests and responses.
 * 
 */
public class CallBackHandler implements SOAPHandler<SOAPMessageContext> {

	@Override
	public boolean handleMessage(SOAPMessageContext context) {
		Boolean isOutbound = (Boolean) context
				.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY);
		if (!isOutbound) {
			try {
				SOAPEnvelope envelope = context.getMessage().getSOAPPart()
						.getEnvelope();
				SOAPHeader header = envelope.getHeader();

				/* store in application context the relatesTo field */
				context.put("RelatesTo", getRelatesTo(header));
				context.setScope("RelatesTo", Scope.APPLICATION);

				/* extract the generated MessageID */
				String messageID = getMessageID(header);
				context.put("MessageID", messageID);
				context.setScope("MessageID", Scope.APPLICATION);
					
			} catch (Exception ex) {
				throw new RuntimeException(ex);
			}
		}

		return true;
	}
	
	protected String getMessageID(SOAPHeader header) {
		NodeList nodeListMessageId = header.getElementsByTagName("MessageID");
		return nodeListMessageId.item(0).getTextContent();
	}
	
	protected String getRelatesTo(SOAPHeader header) {
		NodeList nodeListMessageId = header.getElementsByTagName("RelatesTo");
		return nodeListMessageId.item(0).getTextContent();
	}

	@Override
	public void close(MessageContext context) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean handleFault(SOAPMessageContext context) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Set<QName> getHeaders() {
		// TODO Auto-generated method stub
		return null;
	}	

}
